package com.bulletelc.apollopre.module.deal.pay;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.entity.PayTypeBean;
import com.bulletelc.apollopre.entity.PrepayIdDataBean;
import com.bulletelc.apollopre.framework.BasePresenter;
import com.bulletelc.apollopre.utils.MyUtil;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * author: lhl
 * date  : 2018/01/21
 * desc  : TODO
 */

public class PayCenterPresenter extends BasePresenter<PayCenterContract.View> implements PayCenterContract.Presenter {
    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void getPayType() {
        getPayTypeImp();
    }

    @Override
    public void getPrepayId(String json,String token) {
        getPrepayIdImp(json,token);
    }

    /**
     * 获取支付方式列表
     */
    private void getPayTypeImp() {
        OkGo.<String>get(NetWorkPath.GET_PAY_TYPE)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken(MyApplication.getToken()))
                .params("PaymentMethod[eshop_id]", 1)
                .params("PaymentMethod[type]", 2)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parsePayType(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorPayType(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析数据
     *
     * @param response
     */
    private void parsePayType(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                String code = metaObj.getString("code");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
                        @Override
                        public boolean shouldSkipField(FieldAttributes f) {
                            return f.getName().contains("_links")|f.getName().contains("commission");
                        }

                        @Override
                        public boolean shouldSkipClass(Class<?> clazz) {
                            return false;
                        }
                    }).create();

                    Type type = new TypeToken<List<PayTypeBean>>() {}.getType();
                    List<PayTypeBean> payTypeBeans = gson.fromJson(object.getJSONArray("data").toString(), type);

                    if (isViewAttached()) {
                        getView().onSuccessPayType(payTypeBeans);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailPayType(metaObj.getString("msg"));
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorPayType("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailPayType(response.body().toString());
            }
        }
    }

    /**
     * 获取预付单号
     */
    private void getPrepayIdImp(String json,String token) {
        RequestBody body=RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON),json);
        OkGo.<String>post(NetWorkPath.POST_PREPAY_ID)
                .headers(NetWorkPath.HEADER_KEY_AUTH,MyUtil.getAuthToken(token))
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parsePrePayId(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorPrepayId(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析生成预付单返回的数据
     * @param response
     */
    private void parsePrePayId(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj=object.getJSONObject("meta");
                String code=metaObj.getString("code");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                    Gson gson = new Gson();
                    PrepayIdDataBean prepayIdDataBean=gson.fromJson(object.getJSONObject("data").toString(), PrepayIdDataBean.class);
                    if (isViewAttached()) {
                        getView().onSuccessPrepayId(prepayIdDataBean);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailPrepayId(metaObj.getString("msg"));
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()){
                    getView().onErrorPrepayId("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailPrepayId(response.body().toString());
            }
        }
    }
}
